//
//  EditViewController.m
//  笔记1
//
//  Created by  on 2022/11/5.
//

#import "EditViewController.h"
#import "ImgCell.h"
#import "TextEditViewController.h"
#import "ColorEditViewController.h"
@interface EditViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (strong, nonatomic) IBOutlet UIView *toolbar;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *toolbarBottom;
@property (strong, nonatomic) IBOutlet UITextView *input;
@property (strong, nonatomic) IBOutlet UILabel *plachholder;
@property (strong, nonatomic) IBOutlet UICollectionView *collection;
@end

@implementation EditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    [self updateUI];
}
- (void)initUI{
    [self.collection registerNib:[ImgCell nib] forCellWithReuseIdentifier:[ImgCell ID]];
}
- (void)updateUI{
    NSString *icon = self.isedit ? @"勾":@"编辑";
    [self.rightBtn setImage:[UIImage imageNamed:icon] forState:UIControlStateNormal];
    self.title = [NSDate transToDate:LS(@"yyyy年MM月") :self.model.stamp];
    self.input.userInteractionEnabled = self.isedit;
    self.input.text = self.model.content;
    self.input.textHexColor = self.model.textColor;
    self.input.font = [UIFont systemFontOfSize:self.model.font];
    self.input.bgHexColor = self.model.bgColor;
    self.collection.bgHexColor = self.model.bgColor;
    self.view.bgHexColor = self.model.bgColor;
    self.plachholder.hidden = self.model.content.length > 0;
    [self.collection reloadData];
}

- (void)rightBtnAction{
    if (self.isedit == NO) {
        self.isedit = YES;
        return [self updateUI];
    }
    if (self.model.content.length <= 0) {
        return [CCHud msg:LS(@"内容不能为空")];
    }else if (self.model.imgs.count <= 0){
        return [CCHud msg:LS(@"至少选择一张图片")];
    }else if (self.model.name <= 0){
        return [InputViewController show:^(NSString * _Nonnull string) {
            self.model.name = string;
            [self rightBtnAction];
        }];
    }
    self.model.isFile = NO;
    [NoteTool update:self.model complete:^(BOOL success) {
        [self backBtnAction];
    }];
}
- (IBAction)actionForBtn:(UIButton *)sender {
    if (self.isedit == NO) {
        return;
    }
    WS(self)
    if (sender.tag == 201) {
        TextEditViewController *vc = [TextEditViewController new];
        vc.fontBlock = ^(CGFloat font) {
            weakself.model.font = font;
            [weakself updateUI];
        };
        vc.colorBlock = ^(NSString * _Nonnull color) {
            weakself.model.textColor = color;
            [weakself updateUI];
        };
        [self presentViewController:vc animated:NO completion:nil];
    }else if (sender.tag == 202){
        SheetViewController *sheetvc = [SheetViewController new];
        sheetvc.withCancel = NO;
        sheetvc.array = @[@"拍摄",@"相册",@"取消"];
        WS(sheetvc)
        sheetvc.block = ^(int index, NSString * _Nonnull text) {
            if ([text isEqualToString:LS(@"取消")]) {
                return [weaksheetvc dismissViewControllerAnimated:NO completion:nil];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [CCHud startHud];
            });
            UIImagePickerController *vc = [UIImagePickerController new];
            vc.delegate = weakself;
            vc.allowsEditing = YES;
            vc.sourceType = index == 0 ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypePhotoLibrary;
            vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
            [[weakself currentVC] presentViewController:vc animated:YES completion:^{
                [CCHud stopHud];
            }];
        };
        [[weakself currentVC] presentViewController:sheetvc animated:NO completion:nil];
    }else if (sender.tag == 203){
        ColorEditViewController *vc = [ColorEditViewController new];
        vc.colorBlock = ^(NSString * _Nonnull color) {
            weakself.model.bgColor = color;
            [weakself updateUI];
        };
        [self presentViewController:vc animated:NO completion:nil];
    }
}
#pragma mark - UIImagePickerControllerDelegate / UINavigationControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    UIImage *img = info[UIImagePickerControllerEditedImage];
    NSData *data = UIImageJPEGRepresentation(img, 0.5);
    if (self.model) {
        [self.model.imgs addObject:data];
    }
    [self updateUI];
    [picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - UITextViewDelegate
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    self.plachholder.hidden = YES;
    return YES;
}
- (void)textViewDidChange:(UITextView *)textView{
    self.model.content = textView.text;
    self.plachholder.hidden = textView.text.length > 0;
}
#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.model.imgs.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ImgCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:[ImgCell ID] forIndexPath:indexPath];
    cell.img.image = [UIImage imageWithData:self.model.imgs[indexPath.row]];
    WS(self)
    cell.block = ^{
        if (self.isedit) {
            [weakself.model.imgs removeObjectAtIndex:indexPath.row];
            [weakself updateUI];
        }
    };
    return  cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return  CGSizeMake((SCREEN_WIDTH - 40), self.collection.frame.size.height - 40);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return  UIEdgeInsetsMake(20, 20, 20, 20);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 20;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}

@end

